import { Context } from 'elysia';
import { db } from '../db';
import { contacts } from '../db/schema';
import { eq, desc, and } from 'drizzle-orm';
import { createId } from '@paralleldrive/cuid2';
import { Logger } from '../utils/response';
import { logUserOperation, logDatabaseOperation } from '../utils/systemLogger';
import { checkReadOnlyAccess } from '../middleware/auth';

// 获取所有联系人（管理端）
export const getContacts = async ({ set }: Context) => {
  try {
    const contactList = await db
      .select()
      .from(contacts)
      .orderBy(desc(contacts.sort), desc(contacts.createdAt));

    return {
      success: true,
      data: contactList
    };
  } catch (error) {
    Logger.error('获取联系人列表失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '获取联系人列表失败'
    };
  }
};

// 获取公开联系人信息（前台展示）- 限制最多返回2个联系人
export const getPublicContacts = async ({ set }: Context) => {
  try {
    const contactList = await db
      .select({
        id: contacts.id,
        name: contacts.name,
        position: contacts.position,
        phone: contacts.phone,
        wechat: contacts.wechat,
        email: contacts.email,
        avatar: contacts.avatar,
        description: contacts.description,
        expertise: contacts.expertise,
        workHours: contacts.workHours
      })
      .from(contacts)
      .where(eq(contacts.status, 'active'))
      .orderBy(desc(contacts.sort), desc(contacts.createdAt))
      .limit(2);

    return {
      success: true,
      data: contactList
    };
  } catch (error) {
    Logger.error('获取公开联系人信息失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '获取联系人信息失败'
    };
  }
};

// 获取单个联系人
export const getContact = async ({ params, set }: Context) => {
  try {
    const { id } = params as { id: string };
    
    const contact = await db
      .select()
      .from(contacts)
      .where(eq(contacts.id, id))
      .limit(1);

    if (contact.length === 0) {
      set.status = 404;
      return {
        success: false,
        message: '联系人不存在'
      };
    }

    return {
      success: true,
      data: contact[0]
    };
  } catch (error) {
    Logger.error('获取联系人失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '获取联系人失败'
    };
  }
};

// 创建联系人
export const createContact = async ({ body, set, user }: Context) => {
  try {
    // 检查权限
    const accessCheck = checkReadOnlyAccess(user, 'POST');
    if (!accessCheck.allowed) {
      set.status = 403;
      return {
        success: false,
        message: accessCheck.message
      };
    }
    const contactData = body as {
      name: string;
      position?: string;
      phone: string;
      wechat?: string;
      email?: string;
      avatar?: string;
      description?: string;
      expertise?: string;
      workHours?: string;
      qq?: string;
      sort?: number;
    };

    const id = createId();
    const now = new Date().toISOString();

    await db.insert(contacts).values({
      id,
      name: contactData.name,
      position: contactData.position,
      phone: contactData.phone,
      wechat: contactData.wechat,
      email: contactData.email,
      avatar: contactData.avatar,
      description: contactData.description,
      expertise: contactData.expertise,
      workHours: contactData.workHours,
      qq: contactData.qq,
      sort: contactData.sort || 0,
      status: 'active',
      createdAt: now,
      updatedAt: now
    });

    // 记录系统日志
    await logDatabaseOperation(
      'contact',
      'create',
      `创建联系人: ${contactData.name}`,
      { contactId: id, position: contactData.position, phone: contactData.phone }
    );

    Logger.info(`联系人创建成功: ${contactData.name}`);

    return {
      success: true,
      data: { id },
      message: '联系人创建成功'
    };
  } catch (error) {
    Logger.error('创建联系人失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '创建联系人失败'
    };
  }
};

// 更新联系人
export const updateContact = async ({ params, body, set, user }: Context) => {
  try {
    // 检查权限
    const accessCheck = checkReadOnlyAccess(user, 'PUT');
    if (!accessCheck.allowed) {
      set.status = 403;
      return {
        success: false,
        message: accessCheck.message
      };
    }
    const { id } = params as { id: string };
    const updateData = body as Partial<{
      name: string;
      position: string;
      phone: string;
      wechat: string;
      email: string;
      avatar: string;
      description: string;
      expertise: string;
      workHours: string;
      qq: string;
      sort: number;
      status: string;
    }>;

    // 检查联系人是否存在
    const existingContact = await db
      .select()
      .from(contacts)
      .where(eq(contacts.id, id))
      .limit(1);

    if (existingContact.length === 0) {
      set.status = 404;
      return {
        success: false,
        message: '联系人不存在'
      };
    }

    await db
      .update(contacts)
      .set({
        ...updateData,
        updatedAt: new Date().toISOString()
      })
      .where(eq(contacts.id, id));

    // 记录系统日志
    await logDatabaseOperation(
      'contact',
      'update',
      `更新联系人: ${existingContact[0].name}`,
      { contactId: id, updatedFields: Object.keys(updateData) }
    );

    Logger.info(`联系人更新成功: ${id}`);

    return {
      success: true,
      message: '联系人更新成功'
    };
  } catch (error) {
    Logger.error('更新联系人失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '更新联系人失败'
    };
  }
};

// 删除联系人
export const deleteContact = async ({ params, set, user }: Context) => {
  try {
    // 检查权限
    const accessCheck = checkReadOnlyAccess(user, 'DELETE');
    if (!accessCheck.allowed) {
      set.status = 403;
      return {
        success: false,
        message: accessCheck.message
      };
    }
    const { id } = params as { id: string };

    // 检查联系人是否存在
    const existingContact = await db
      .select()
      .from(contacts)
      .where(eq(contacts.id, id))
      .limit(1);

    if (existingContact.length === 0) {
      set.status = 404;
      return {
        success: false,
        message: '联系人不存在'
      };
    }

    await db
      .delete(contacts)
      .where(eq(contacts.id, id));

    // 记录系统日志
    await logDatabaseOperation(
      'contact',
      'delete',
      `删除联系人: ${existingContact[0].name}`,
      { contactId: id, position: existingContact[0].position }
    );

    Logger.info(`联系人删除成功: ${id}`);

    return {
      success: true,
      message: '联系人删除成功'
    };
  } catch (error) {
    Logger.error('删除联系人失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '删除联系人失败'
    };
  }
};

// 批量更新联系人排序
export const updateContactsSort = async ({ body, set, user }: Context) => {
  try {
    // 检查权限
    const accessCheck = checkReadOnlyAccess(user, 'PUT');
    if (!accessCheck.allowed) {
      set.status = 403;
      return {
        success: false,
        message: accessCheck.message
      };
    }
    const { contacts: contactsToUpdate } = body as {
      contacts: Array<{ id: string; sort: number }>;
    };

    // 批量更新排序
    for (const contact of contactsToUpdate) {
      await db
        .update(contacts)
        .set({
          sort: contact.sort,
          updatedAt: new Date().toISOString()
        })
        .where(eq(contacts.id, contact.id));
    }

    Logger.info(`批量更新联系人排序成功，共更新 ${contactsToUpdate.length} 个联系人`);

    return {
      success: true,
      message: '联系人排序更新成功'
    };
  } catch (error) {
    Logger.error('批量更新联系人排序失败:', error);
    set.status = 500;
    return {
      success: false,
      message: '更新联系人排序失败'
    };
  }
};